<template>
  <!--新技审页面-->
  <div class="technical_page">
    <div class="btns" style="padding:1em;margin-bottom:1em;background:#fff">
      <el-select v-model="searchForm.condition" placeholder="请选择业务范围" @change="conditionChange">
        <el-option-group label="个人业务">
          <el-option key="1" label="未审核(Person)" value="1"></el-option>
          <el-option key="2" label="已审核(Person)" value="2"></el-option>
        </el-option-group>
        <el-option-group label="全部业务">
          <el-option key="3" label="未审核(ALL)" value="3"></el-option>
          <el-option key="4" label="已审核(ALL)" value="4"></el-option>
        </el-option-group>
      </el-select>
      <el-select v-model="searchForm.proDetailId" style="margin-right: 6px" filterable clearable placeholder="请选择项目" value-key="name">
        <el-option v-for="item in projects" :key="item.proId" :label="item.proName" :value="item.proId">
          <span>{{item.proName}}</span>
          <el-tag size="mini" :type="item.audit != 0? 'success':'warning'" style="float: right;transform: translate(0, 7px)">{{item.status}}</el-tag>
        </el-option>
      </el-select>
      <el-button style="margin-right: 6px" type="primary" icon="el-icon-search" size="small" @click="toSearch">查询</el-button>
      <el-link v-for="item in files" :key="item.id" type="primary" :download="item.name" target="_blank" :href = "item.url">{{item.name}} | </el-link>
    </div>
    <div style="padding:1em;margin-bottom:1em;background:#fff">
      <a-table
      class="table2"
      :loading="table.loading"
      size="middle"
      :data-source="table.data"
      :customRow="rowClick"
      :pagination="table.pagination"
      :row-class-name="tableRowClassName"
      :scroll="{ x: 786, y: tableHeight }"
      :rowKey="record => record.id"
      >
        <a-table-column v-show="item.dataIndex!='brand'" v-for="item in currentTemplate.tableColumn"
                        :width="item.width" :align="item.align" :key="item.key" :title="item.title" :dataIndex="item.dataIndex">
        </a-table-column>
        <a-table-column :width="100" align="center" key="total" title="需审核数量" data-index="total">
          <template slot-scope="text">
            <el-tag>{{text}}</el-tag>
          </template>
        </a-table-column>
      </a-table>
    </div>

    <!--审核内容模态框-->
    <el-dialog v-el-drag-dialog title="报价单" :visible.sync="checkDialog.visible" @close="checkDialogCancel">
      <el-button v-show="checkDialog.table.selected.length>0" type="primary" size="small" @click="toCheck(key=1)">通过</el-button>
      <el-button v-show="checkDialog.table.selected.length>0" type="danger" size="small" @click="toCheck(key=2)">拒绝</el-button>
      <el-button v-show="checkDialog.table.selected.length>0" type="info" size="small" @click="toCheck(key=0)">撤销</el-button>
      <div class="el-dialog__body">
        <span style="padding: 10px">【{{inquiry.name}}】| 【{{inquiry.params}}】</span>
        <a-table
        :loading="checkDialog.table.loading"
        class="table1"
        size="middle"
        :data-source="checkDialog.table.data"
        :rowKey="record => record.checkId"
        :row-selection="{ selectedRowKeys: checkDialog.table.selected, onChange: onSelectChange }">
        >
        <a-table-column align="center" key="supplier" title="供货商" data-index="supplier" ellipsis="true"/>
        <a-table-column align="center" key="dataSource" title="来源" data-index="dataSource">
          <template slot-scope="text">
            <el-tag v-if="text == 0" type="warning">{{"产品池"}}</el-tag>
            <el-tag v-else-if="text == 1" type="success">{{"市场"}}</el-tag>
          </template>
        </a-table-column>
        <a-table-column align="center" key="tecA" title="状态" data-index="tecA">
          <template slot-scope="text">
            <el-tag v-if="text == 0" type="info">{{"未审核"}}</el-tag>
            <el-tag v-else-if="text == 1" type="success">{{"通过"}}</el-tag>
            <el-tag v-else-if="text == 2" type="danger">{{"否决"}}</el-tag>
          </template>
        </a-table-column>
        <a-table-column align="center" key="tecSR" title="应审核人" data-index="tecSR" ellipsis="true"/>
        <a-table-column width="200px" align="center" key="model" title="型号" data-index="model"/>
        <a-table-column align="center" key="brand" title="品牌" data-index="brand" ellipsis="true"/>
        <a-table-column width="200px" align="center" key="params" title="参数" data-index="params"/>
        <a-table-column align="center" key="delivery" title="货期" data-index="delivery" ellipsis="true"/>
        <a-table-column align="center" key="warranty" title="质保期" data-index="warranty" ellipsis="true"/>
        <a-table-column align="center" key="image" title="图片">
          <template slot-scope="text">
            <div v-for="(item, key) in text.image" :key="key">
              <el-image fit="contain" style="height: 40px; width:auto" :src="item" :preview-src-list="[item]" v-if="item!=null && item != ''">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
          </template>
        </a-table-column>
        <a-table-column width="200px" align="center" key="remark" title="商家备注" data-index="remark"/>
        <a-table-column align="center" key="file" title="文件">
          <template slot-scope="text">
            <el-tag v-for="(item, key) in text.file" :key="key" effect="plain" type="primary">
              <a style="display: block" class="ellipsis" :href="item.url" :download="item.name" target="_blank">{{item.name}}</a>
            </el-tag>
          </template>
        </a-table-column>
        <a-table-column align="center" key="tecRemark" title="审核备注" data-index="tecRemark" ellipsis="true"/>
      </a-table>
      </div>
    </el-dialog>

    <!--技审备注模态框-->
    <el-dialog v-el-drag-dialog title="填写备注" :visible.sync="remarkDialog.visible">
      <el-form ref="remarkDialog.form" :rules="remarkDialog.codeRules" :model="remarkDialog.form"  status-icon>
        <el-form-item label="技审备注" label-width="80px" size="small" prop="remark">
          <el-input type="text" v-model="remarkDialog.form.technicalRemark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="remarkDialog.visible = false">取 消</el-button>
        <el-button type="primary" size="small" :loading="remarkDialog.subLoading" @click="submitHandler('remarkDialog.form')">提 交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

  import { getAction, postActionByJson, postActionByQueryString } from '@/api/manage'
  import elDragDialog from '@/directive/el-drag-dialog'
  import '@/styles/auto-style.css'


  export default {
    directives: { elDragDialog },
    name: 'technical',

    data(){
      return{
        //缓存对象(模态框显示内容)
        inquiry: {},
        files: [],
        inquiryId: null,
        remarkDialog: {
          subLoading: false,
          visible: false,
          form: {},
          codeRules: {
            technicalRemark: [
              {required: true, message: '不能为空', trigger: 'blur'}
            ],
          }
        },
        checkDialog: {
          visible: false,
          table:{
            loading: false,
            data: [],
            selected: [],
          }
        },
        //当前模板
        searchForm: { condition: null },
        projects: [],
        currentTemplate: {tableColumn: []},
        table: {
          loading: false,
          data: [],
          selected: [],
          pagination: {
            showTotal: total => `共 ${total} 条结果`,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            current: 1,
            pageSize: 10,
            total: 0,
            onChange: (item) => {
              this.table.pagination.current = item
              this.toSearch()
            },
            onShowSizeChange: (current, pageSize) => {
              this.table.pagination.pageSize = pageSize
              this.toSearch()
            }, // 改变每页数量时更新显示
          }
        },
        url: {
          findTechnicalCheckPro: '/proCheck/findTechnicalCheckPro',
          findTechnicalItem: '/proCheck/findTechnicalItem',
          findInquiryTemplate: '/inquiry/template/findInquiryTemplate',
          findTechnicalCheckQuote: '/proCheck/findTechnicalCheckQuote',
          updateTechnicalStatus: '/proCheck/updateTechnicalStatus',
          findByProId: '/file/findByProId'
        },
        //屏幕高度
        tableHeight: document.documentElement.clientHeight-98-196,
      }
    },
    created() {
      if(this.$route.query && this.$route.query.proId && this.$route.query.status){
        this.searchForm.condition = this.$route.query.status
        this.searchForm.proDetailId = this.$route.query.proId
        this.toSearch()
        this.searchForm = {}
      }
    },
    methods: {
      checkDialogCancel(){
        this.checkDialog.visible = false
        this.toSearch()
      },
      submitHandler(form){
        this.$refs[form].validate((valid) => {
          if(valid){
            this.remarkDialog.subLoading = true
            this.remarkDialog.form.id = this.checkDialog.table.selected[0]
            const data = []
            data.push(this.remarkDialog.form)
            postActionByJson(this.url.updateTechnicalStatus, data)
            .then(resp =>{
              this.$message.success(resp.message + '条更新')
            }).catch(()=>{
              this.$message.error('提交失败')
            }).finally(()=>{
              this.remarkDialog.subLoading = false
              this.remarkDialog.visible = false
              this.toFindQuote()
            })
          }
        })
      },
      toCheck(key){
        if (key === 2){
          if (this.checkDialog.table.selected.length > 1){
            this.$message({ type: 'warning', message: '否决不能多选'})
            return
          }
        }
        if (this.checkDialog.table.selected.length > 1){
          //多选不弹窗
          this.$confirm('是否确定选择？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const data = []
            this.checkDialog.table.selected.map(item =>{
              const obj = {}
              obj["id"] = item
              obj["technicalAudit"] = key
              obj["technicalRemark"] = ''
              data.push(obj)
            })
            postActionByJson(this.url.updateTechnicalStatus, data)
            .then(resp =>{
              this.$message.success(resp.message + '条更新')
            }).catch(()=>{
              this.$message.error('提交失败')
            }).finally(()=>{
              this.toFindQuote()
            })
          })
          return
        }
        if (this.checkDialog.table.selected.length === 1){
          this.remarkDialog.form.technicalAudit = key
          this.remarkDialog.visible = true
        }
      },
      tableRowClassName(row, index){
        if (row.refuseStatus === 1) {
          return 'danger-row';
        }
        return '';
      },
      toFindQuote(){
        this.checkDialog.table.loading = true
        this.checkDialog.table.selected = []
        getAction(this.url.findTechnicalCheckQuote, {inquiryId: this.inquiryId})
        .then(resp =>{
          this.checkDialog.table.data = resp.data
          this.checkDialog.table.data.forEach(x =>{
            if(x.image){
              let img
              img = x.image.split(',')
              if(img.length > 0){
                //移除最后一个元素
                img.pop()
                x.image = img
                console.info(img)
              }
            }
          })
        }).catch((e)=>{
          this.$message.error(e)
        }).finally(()=>{
          this.checkDialog.table.loading = false
        })
      },
      onSelectChange(ids, rows){
        this.checkDialog.table.selected = []
        const itemsId = []
        rows.map(item => {
          itemsId.push(item.checkId)
        })
        this.checkDialog.table.selected = itemsId
        console.info(itemsId)
      },
      rowClick(row, index){
        return {
         on: {
           click: ()=>{
             this.checkDialog.visible = true
             this.inquiryId = row.id
             this.inquiry.name = row.name
             this.inquiry.params = row.params
             this.toFindQuote()
           }
         }
        }
      },
      async loadCurrentTemplate(id) {
        if (id > 0) {
          await getAction(this.url.findInquiryTemplate, {id: id})
            .then(resp => {
              if (resp.data){
                this.currentTemplate = resp.data[0]
                this.currentTemplate.tableColumn = JSON.parse(resp.data[0].tableColumn)
              }
            })
            .catch(()=> {
              this.$message.error('模板查询失败')
            })
        }else {
          this.$message.error('缺失模版,请选择相对于的模版，否则后续无法继续操作')
        }
      },
      conditionChange(){
        if (this.searchForm.condition){
          this.$delete(this.searchForm, 'proDetailId')
          this.loadProjects()
        }
      },
      toSearch() {
        this.table.loading = true
        this.searchForm.pageSize = this.table.pagination.pageSize
        this.searchForm.pageNum = this.table.pagination.current
        getAction(this.url.findTechnicalItem, this.searchForm)
        .then(async resp =>{
          if (resp.data){
            this.table.pagination.current = parseInt(resp.data.current)
            this.table.pagination.pageSize = parseInt(resp.data.size)
            this.table.pagination.total = parseInt(resp.data.total)
            if (resp.data.records.length > 0){
              this.table.data = resp.data.records
              await this.loadCurrentTemplate(resp.data.records[0].templateId)
            }
          }
        }).catch(()=>{
          this.$message.error('查询失败')
        }).finally(()=>{
          this.table.loading = false
          this.loadProFile()
        })
      },
      loadProjects() {
        getAction(this.url.findTechnicalCheckPro, {status: this.searchForm.condition})
        .then(response => {
          this.projects = response.data
        }).catch(()=>{
          this.$message.error('项目预加载失败')
        })
      },
      loadProFile(){
        if (this.searchForm.proDetailId){
          getAction(this.url.findByProId,{ proId : this.searchForm.proDetailId})
          .then(resp => {
            this.files = resp.data
          }).catch(()=>{
            this.$message.error('项目文件加载失败')
          })
        }
      }
    }
  }

</script>

<style lang="scss" scoped>
  .technical_page{

    .table1{
      padding: 10px;
      
    }
  }
  /deep/.table2{
    .danger-row {
      background: #f1b7b7;
    }
  }
  /deep/.el-dialog{
    min-width: 1500px;
  }
  .el-dialog__body{
    flex: 1;
    overflow: auto;
  }
</style>
